<template>
  <div>
    <div ref="chart" style="width: 60%; height: 600px"></div>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import { getToken } from "@/utils/auth";
/* import { WAREHOUSES_PATH } from "../../../api/constants/constants.js"; */


export default {
  name: "DeviceChart",
  mounted() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      try {
        const token = getToken();
        const response = await axios.get(
           `${process.env.VUE_APP_BASE_API}/wareHouses/sqm`, {
      
          headers: {
            Authorization: `Bearer ${token}`, 
          },
        });
        // console.log("Received data11:", response.data); 
        // console.log("Data to render:", data);

        this.renderChart(response.data);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },
    renderChart(data) {
      // console.log(data);

      const chart = echarts.init(this.$refs.chart);
      // console.log("Initialized chart:", chart);

      const deviceNumbers = Object.keys(data).map((key) => key);
      // console.log("deviceNumbers:", deviceNumbers);
      // 从 data 对象中获取所有的值，并将其映射为一个新数组
      // 其中每个元素是原始值对象中的 '次数' 属性
      const faultCounts = Object.values(data).map(item => item.frequency);
      // console.log("faultCounts:", faultCounts);

      const option = {
        title: {
          text: "故障次数最多的前10个设备",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          data: ["故障次数"],
        },
        xAxis: {
          type: "category",
          data: deviceNumbers,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "故障次数",
            type: "bar",
            data: faultCounts,
          },
        ],
      };

      chart.setOption(option);
      console.log("Set option:", option);
    },
  },
};
</script>

<style scoped>
#chart {
  margin: 20px;
}
</style>
